var wrapper = document.getElementById("signature-pad");
var clearButton = wrapper.querySelector("[data-action=clear]");
var savePNGButton = wrapper.querySelector("[data-action=save-png]");
var backButton = wrapper.querySelector("[data-action=back]");
var canvas = wrapper.querySelector("canvas");
var signaturePad = new SignaturePad(canvas, {
  minWidth: 3,
  maxWidth: 5,
  backgroundColor: 'rgb(255, 255, 255)',
  onEnd: function() {
    endOri = currentOri;
  }
});
var reqURL = 'https://neom.cgnpc.com.cn/esb/snerdi.service.zeng.interfaces.signature';
var id = '';
var currentOri = 0;
var endOri = 0;

function rotateBase64Img(src, edg, callback) {
 
      var canvas = document.createElement("canvas");
      var ctx = canvas.getContext("2d");
 
      var imgW;//图片宽度
      var imgH;//图片高度
      var size;//canvas初始大小
 
      if (edg % 90 != 0) {
          console.error("旋转角度必须是90的倍数!");
          throw '旋转角度必须是90的倍数!';
      }
      (edg < 0) && (edg = (edg % 360) + 360)
      const quadrant = (edg / 90) % 4; //旋转象限
      const cutCoor = {sx: 0, sy: 0, ex: 0, ey: 0}; //裁剪坐标
 
      var image = new Image();
      image.crossOrigin = "anonymous"
      image.src = src;
 
      image.onload = function () {
 
          imgW = image.width;
          imgH = image.height;
          size = imgW > imgH ? imgW : imgH;
 
          canvas.width = size * 2;
          canvas.height = size * 2;
          switch (quadrant) {
              case 0:
                  cutCoor.sx = size;
                  cutCoor.sy = size;
                  cutCoor.ex = size + imgW;
                  cutCoor.ey = size + imgH;
                  break;
              case 1:
                  cutCoor.sx = size - imgH;
                  cutCoor.sy = size;
                  cutCoor.ex = size;
                  cutCoor.ey = size + imgW;
                  break;
              case 2:
                  cutCoor.sx = size - imgW;
                  cutCoor.sy = size - imgH;
                  cutCoor.ex = size;
                  cutCoor.ey = size;
                  break;
              case 3:
                  cutCoor.sx = size;
                  cutCoor.sy = size - imgW;
                  cutCoor.ex = size + imgH;
                  cutCoor.ey = size + imgW;
                  break;
          }
 
 
          ctx.translate(size, size);
          ctx.rotate(edg * Math.PI / 180);
          ctx.drawImage(image, 0, 0);
 
          var imgData = ctx.getImageData(cutCoor.sx, cutCoor.sy, cutCoor.ex, cutCoor.ey);
          if (quadrant % 2 == 0) {
              canvas.width = imgW;
              canvas.height = imgH;
          } else {
              canvas.width = imgH;
              canvas.height = imgW;
          }
          ctx.putImageData(imgData, 0, 0);
          callback(canvas.toDataURL(),canvas)
      };
}


function getUrlVars()
{
  var vars = [], hash;
  var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
  for(var i = 0; i < hashes.length; i++)
  {
    hash = hashes[i].split('=');
    vars.push(hash[0]);
    vars[hash[0]] = hash[1];
  }
  return vars;
}
if (window.DeviceOrientationEvent) {
  window.addEventListener('deviceorientation', function(e) {
    currentOri = e.alpha;
  });
}

$(function() {
  id = getUrlVars()["id"];
  $('#loading').html('<img src="rotate.gif" />');
  $('#loading').delay(1000).fadeOut(2000);
  return ;
  $.post(reqURL, {
    ctype: "MAPP_USERHASSEAL",
    ucode: id
  },'json').done(function(data) {
    var result = $.parseJSON(data);
    if (result.success=='1') {
      $('#loading').html('<img src="rotate.gif" />');
      $('#loading').delay(1000).fadeOut(2000);
    }
    else {
      $('#loading').html('<strong>'+result.message+'</strong>');
      $('#direction').hide();
      alert(result.message);
    }
  })
});

function resizeCanvas() {
  var ratio =  Math.max(window.devicePixelRatio || 1, 1);

  // This part causes the canvas to be cleared
  canvas.width = canvas.offsetWidth * ratio;
  canvas.height = canvas.offsetHeight * ratio;
  canvas.getContext("2d").scale(ratio, ratio);
  signaturePad.clear();
}

// On mobile devices it might make more sense to listen to orientation change,
// rather than window resize events.
window.onresize = resizeCanvas;
resizeCanvas();

function download(dataURL, filename) {
  $('#loading').html('<img src="loading.gif" />');
  $('#loading').show();
  return ;
  $.post(reqURL, {
    ctype: "MAPP_USERSEAL",
    ucode: id,
    useal: signaturePad.toDataURL(),
    rotation: endOri,
  }).done(function(data) {
    $('#loading').hide();
    var result = $.parseJSON(data);
    if (result.success=='1') {
      alert("采集完成");
      window.location.reload();
    }
    else {
      alert(result.message)
    }
  });
}

clearButton.addEventListener("click", function (event) {
  signaturePad.clear();
});

backButton.addEventListener("click", function (event) {
  plus.webview.currentWebview().close();
});

savePNGButton.addEventListener("click", function (event) {
  if (signaturePad.isEmpty()) {
    alert("请先手写签名.");
  } else {
    var dataURL = signaturePad.toDataURL();
    var page = plus.webview.currentWebview().opener();
    var id=page.id;
	rotateBase64Img(dataURL,-90,function(data,cav){
		cav.remove(cav.selectedIndex);
		localStorage.setItem('dataURL', data);
		mui.fire(page, 'signUrl',{dataURL:data});
		plus.webview.currentWebview().close();
	})
	return;
  }
});
